<template>
  <view class="buddy-detail-page">
    <!-- 自定义导航栏 -->
    <view class="custom-navbar">
      <view class="navbar-content">
        <view class="navbar-left" @click="goBack">
          <uni-icons type="left" size="24" color="#fff"></uni-icons>
        </view>
        <view class="navbar-title"></view>
        <view class="navbar-right"></view>
      </view>
    </view>

    <!-- 主内容区域 -->
    <scroll-view scroll-y class="content-scroll">
      <!-- 顶部轮播图（在滚动区域内） -->
      <view class="header-background">
        <swiper 
          v-if="buddyDetail.images && buddyDetail.images.length > 0"
          class="header-swiper"
          :indicator-dots="buddyDetail.images.length > 1"
          :autoplay="false"
          :circular="true"
          indicator-color="rgba(255, 255, 255, 0.5)"
          indicator-active-color="#fff"
        >
          <swiper-item v-for="(img, index) in buddyDetail.images" :key="index">
            <image 
              :src="img" 
              class="header-bg-image" 
              mode="aspectFill"
              @click="previewImage(img, index)"
            ></image>
          </swiper-item>
        </swiper>
        <view v-else class="header-bg-placeholder"></view>
      </view>
      
      <view class="content-wrapper">
        <!-- 发布人信息卡片 -->
        <view class="info-card">
          <!-- 标题和价格 -->
          <view class="title-section">
            <view class="title-left">
              <text class="title-text">{{ buddyDetail.title || '加载中...' }}</text>
              <view class="buddy-type-badge">{{ buddyDetail.buddyTypeName || '搭子' }}</view>
              <view class="rating-inline">
                <image src="/static/huo.png" class="rating-icon" mode="aspectFit"></image>
                <text class="rating-text">{{ buddyDetail.publisherRating || '0' }}</text>
              </view>
            </view>
            <text class="price-text">¥{{ buddyDetail.price || 0 }}</text>
          </view>

          <!-- 发布者信息 -->
          <view class="publisher-section">
            <view class="publisher-avatar-wrapper">
              <image 
                :src="buddyDetail.avatar || '/static/avatars/default_avatar.png'" 
                class="publisher-avatar"
                mode="aspectFill"
              ></image>
            </view>
            <view class="publisher-info">
              <text class="publisher-name">{{ buddyDetail.name || '匿名用户' }}</text>
              <view class="publisher-meta">
                <image src="/static/time.png" class="meta-icon" mode="aspectFit"></image>
                <text class="meta-text">{{ buddyDetail.date || '待定' }}</text>
              </view>
              <view class="publisher-tags">
                <view class="tag-item">{{ buddyDetail.restrictions || '男女不限' }}</view>
                <view class="tag-item" v-if="buddyDetail.duration">{{ buddyDetail.duration }}</view>
                <view class="tag-item" v-if="buddyDetail.distance">距离{{ buddyDetail.distance }}</view>
              </view>
            </view>
          </view>
        </view>

        <!-- 参与者卡片 -->
        <view class="info-card" v-if="buddyDetail.participantsCount > 0">
          <view class="participants-section">
            <text class="section-title">与TA们一起 {{ buddyDetail.participantsCount }}/{{ buddyDetail.participantCount }}人</text>
            <view class="participants-list">
              <image 
                v-for="(participant, index) in buddyDetail.participants" 
                :key="index"
                :src="participant.avatar" 
                class="participant-avatar"
                mode="aspectFill"
                @click="goToUserProfile(participant.id)"
              ></image>
            </view>
          </view>
        </view>

        <!-- 集合地点卡片 -->
        <view class="info-card">
          <view class="location-section">
            <text class="section-title">集合地点</text>
            <view class="location-info">
              <image src="/static/location-small.png" class="location-icon" mode="aspectFit"></image>
              <text class="location-text">{{ buddyDetail.location || '位置信息加载中...' }}</text>
            </view>
            <!-- 地图 -->
            <view class="map-container" v-if="buddyDetail.latitude && buddyDetail.longitude">
              <map
                :latitude="Number(buddyDetail.latitude)"
                :longitude="Number(buddyDetail.longitude)"
                :scale="16"
                :markers="locationMarkers"
                :enable-scroll="false"
                :enable-zoom="false"
                class="detail-map"
              ></map>
            </view>
          </view>
        </view>

        <!-- 活动内容卡片 -->
        <view class="info-card" v-if="buddyDetail.content || (buddyDetail.images && buddyDetail.images.length > 1)">
          <view class="content-section">
            <text class="section-title">活动内容</text>
            <text class="content-text" v-if="buddyDetail.content">{{ buddyDetail.content }}</text>
            <!-- 活动图片 -->
            <view class="images-section" v-if="buddyDetail.images && buddyDetail.images.length > 1">
              <image 
                v-for="(img, index) in buddyDetail.images.slice(1)" 
                :key="index"
                :src="img" 
                class="content-image"
                mode="aspectFill"
                @click="previewImage(img, index)"
              ></image>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 底部操作栏 -->
    <view class="bottom-action-bar">
      <button class="contact-btn" @click="contactPublisher">联系TA</button>
      <button class="join-btn" :disabled="joinLoading" @click="joinBuddy">
        {{ joinLoading ? '提交中...' : '立即参与' }}
      </button>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading-overlay">
      <text class="loading-text">加载中...</text>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import BuddyApi from '@/sheep/api/member/buddy';

const buddyId = ref(null);
const buddyDetail = ref({});
const loading = ref(false);
const joinLoading = ref(false); // New state for join button loading
const currentLatitude = ref(null);
const currentLongitude = ref(null);

const formatTime = (timeStr) => {
  if (!timeStr) return '待定';
  try {
    const date = new Date(timeStr);
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    return `${month}月${day}日 ${hours}:${minutes}`;
  } catch (e) {
    return timeStr;
  }
};

const formatDuration = (minutes) => {
  if (!minutes) return '';
  if (minutes < 60) {
    return `${minutes}分钟`;
  }
  const hours = Math.floor(minutes / 60);
  const mins = minutes % 60;
  if (mins === 0) {
    return `${hours}小时`;
  }
  return `${hours}小时${mins}分钟`;
};

const formatGenderLimit = (genderLimit) => {
  if (genderLimit === 1) return '仅限男生';
  if (genderLimit === 2) return '仅限女生';
  return '男女不限';
};

// 计算两点之间的距离（米）
const calculateDistance = (lat1, lon1, lat2, lon2) => {
  if (lat1 === null || lat1 === undefined || lon1 === null || lon1 === undefined ||
      lat2 === null || lat2 === undefined || lon2 === null || lon2 === undefined) {
    return null;
  }
  
  const R = 6371000; // 地球半径（米）
  const dLat = (lat2 - lat1) * Math.PI / 180;
  const dLon = (lon2 - lon1) * Math.PI / 180;
  const a = 
    Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
    Math.sin(dLon / 2) * Math.sin(dLon / 2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  const distance = R * c;
  
  return distance;
};

// 格式化距离显示
const formatDistance = (distance) => {
  if (!distance && distance !== 0) return '';
  if (distance < 1000) {
    return `${Math.round(distance)}m`;
  }
  return `${(distance / 1000).toFixed(1)}km`;
};

const locationMarkers = computed(() => {
  if (!buddyDetail.value.latitude || !buddyDetail.value.longitude) {
    return [];
  }
  return [{
    id: 1,
    latitude: Number(buddyDetail.value.latitude),
    longitude: Number(buddyDetail.value.longitude),
    iconPath: '/static/map-icon.png',
    width: 30,
    height: 30,
  }];
});

const loadBuddyDetail = async () => {
  if (!buddyId.value) {
    uni.showToast({
      title: '缺少搭子ID',
      icon: 'none'
    });
    return;
  }

  loading.value = true;
  try {
    const res = await BuddyApi.getBuddyOrderDetail(buddyId.value);
    if (res && res.code === 0 && res.data) {
      const data = res.data;
      
      // 格式化数据
      const acceptUsers = Array.isArray(data.acceptUsers) ? data.acceptUsers : [];
      // 保存完整的参与者信息（包括用户ID和头像）
      const participants = acceptUsers.map(user => ({
        id: user.id || user.userId || null,
        avatar: user.avatar || '/static/avatars/default_avatar.png',
        nickname: user.nickname || user.name || '匿名用户'
      }));

      // 计算距离
      let distanceText = '';
      if (currentLatitude.value && currentLongitude.value && data.latitude && data.longitude) {
        const distance = calculateDistance(
          currentLatitude.value,
          currentLongitude.value,
          data.latitude,
          data.longitude
        );
        if (distance !== null) {
          distanceText = formatDistance(distance);
        }
      }

      buddyDetail.value = {
        id: data.id,
        title: data.title || '',
        price: data.unitPrice || 0,
        avatar: data.publisherAvatar || '/static/avatars/default_avatar.png',
        name: data.publisherNickname || '匿名用户',
        publisherRating: data.publisherRating || 0,
        date: data.startTime ? formatTime(data.startTime) : '待定',
        location: data.location || '',
        latitude: data.latitude,
        longitude: data.longitude,
        buddyTypeName: data.buddyTypeName || '搭子',
        restrictions: formatGenderLimit(data.genderLimit),
        duration: formatDuration(data.duration),
        distance: distanceText,
        content: data.content || data.description || '',
        images: data.images || [],
        // 基于 acceptUsers 展示所有已接单用户信息（包括ID和头像）
        participants: participants,
        participantsCount: acceptUsers.length,
        participantCount: data.participantCount || 0,
        maxParticipants: data.maxParticipants || 10,
      };
    } else {
      uni.showToast({
        title: res?.msg || '获取详情失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('获取搭子详情失败:', error);
    uni.showToast({
      title: '获取详情失败，请重试',
      icon: 'none'
    });
  } finally {
    loading.value = false;
  }
};

const goBack = () => {
  uni.navigateBack();
};

const contactPublisher = () => {
  // TODO: 实现联系发布者功能
  uni.showToast({
    title: '联系功能开发中',
    icon: 'none'
  });
};

const joinBuddy = async () => {
  if (joinLoading.value) {
    return;
  }

  const orderId = buddyDetail.value?.id;
  if (!orderId) {
    uni.showToast({
      title: '搭子信息缺失',
      icon: 'none'
    });
    return;
  }

  joinLoading.value = true;
  try {
    const res = await BuddyApi.acceptBuddyOrder({
      buddyOrderId: orderId,
    });

    if (res?.code === 0) {
      uni.showToast({
        title: '已提交参与申请',
        icon: 'success'
      });
    } else {
      uni.showToast({
        title: res?.msg || '参与失败，请重试',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('接受搭子订单失败:', error);
    uni.showToast({
      title: '参与失败，请稍后重试',
      icon: 'none'
    });
  } finally {
    joinLoading.value = false;
  }
};

const previewImage = (current, index) => {
  const images = buddyDetail.value.images || [];
  uni.previewImage({
    current: current,
    urls: images,
  });
};

const goToUserProfile = (userId) => {
  if (userId) {
    uni.navigateTo({
      url: `/pages/user/profile?userId=${userId}`
    });
  } else {
    uni.showToast({
      title: '用户信息缺失',
      icon: 'none'
    });
  }
};

// 获取当前位置
const getCurrentLocation = () => {
  uni.getLocation({
    type: 'gcj02',
    success: (res) => {
      currentLatitude.value = res.latitude;
      currentLongitude.value = res.longitude;
      // 获取位置后重新加载详情（如果已经加载过）
      if (buddyDetail.value.id) {
        loadBuddyDetail();
      }
    },
    fail: (err) => {
      console.error('获取位置失败:', err);
    }
  });
};

onLoad((options) => {
  if (options.id) {
    buddyId.value = options.id;
    // 先获取当前位置，然后加载详情
    getCurrentLocation();
    loadBuddyDetail();
  } else {
    uni.showToast({
      title: '缺少搭子ID',
      icon: 'none'
    });
    setTimeout(() => {
      goBack();
    }, 1500);
  }
});
</script>

<style lang="scss" scoped>
.buddy-detail-page {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f5f5;
  position: relative;
  padding-top: env(safe-area-inset-top);
  padding-top: constant(safe-area-inset-top);
}

.custom-navbar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  padding-top: env(safe-area-inset-top);
  padding-top: constant(safe-area-inset-top);
  background: linear-gradient(to bottom, rgba(0, 0, 0, 0.3), transparent);

  .navbar-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 88rpx;
    padding: 0 30rpx;

    .navbar-left {
      width: 60rpx;
      height: 60rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: rgba(0, 0, 0, 0.3);
      border-radius: 50%;
    }

    .navbar-title {
      flex: 1;
    }

    .navbar-right {
      width: 60rpx;
    }
  }
}

.header-background {
  width: 100%;
  height: 100vw; /* 正方形，宽度等于视口宽度 */
  position: relative;
  z-index: 1; /* 轮播图在最底层 */
  overflow: hidden;

  .header-swiper {
    width: 100%;
    height: 100%;
  }

  .header-bg-image {
    width: 100%;
    height: 100%;
  }

  .header-bg-placeholder {
    width: 100%;
    height: 100%;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  }
}

.content-scroll {
  position: relative;
  height: 100vh;
  box-sizing: border-box;
  z-index: 10; 
}

.content-wrapper {
  padding: 0 17rpx;
  padding-top: 0;
  padding-bottom: 140rpx;
  margin-top: -120rpx; /* 向上移动，覆盖轮播图一部分 */
  box-sizing: border-box;
  position: relative;
  z-index: 10;
}

.info-card {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  position: relative;
  z-index: 10;
  overflow: hidden;

  &::after {
    content: '';
    position: absolute;
    top: 20rpx;
    right: 20rpx;
    width: 160rpx;
    height: 160rpx;
    background-image: url('/static/game.png');
    background-repeat: no-repeat;
    background-size: contain;
    background-position: center;
    opacity: 0.12;
    pointer-events: none;
    z-index: 0;
  }

  > * {
    position: relative;
    z-index: 1;
  }
}

.title-section {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20rpx;

  .title-left {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    flex: 1;
    min-width: 0;

    .title-text {
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
      margin-right: 12rpx;
    }

    .buddy-type-badge {
      padding: 6rpx 16rpx;
      border-radius: 20rpx;
      font-size: 22rpx;
      color: #333;
      background: rgba(252, 231, 152, 0.42);
      margin-right: 16rpx;
      white-space: nowrap;
    }

    .rating-inline {
      display: flex;
      align-items: center;
      flex-shrink: 0;

      .rating-icon {
        width: 28rpx;
        height: 28rpx;
        margin-right: 6rpx;
      }

      .rating-text {
        font-size: 24rpx;
        color: #ED483D;
        font-weight: bold;
      }
    }
  }

  .price-text {
    font-size: 36rpx;
    font-weight: bold;
    color: #ED483D;
    flex-shrink: 0;
    margin-left: 20rpx;
  }
}

.publisher-section {
  display: flex;
  align-items: flex-start;

  .publisher-avatar-wrapper {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-right: 20rpx;
    flex-shrink: 0;

    .publisher-avatar {
      width: 100rpx;
      height: 100rpx;
      border-radius: 50%;
      margin-bottom: 12rpx;
    }
  }

  .publisher-info {
    flex: 1;
    min-width: 0;

    .publisher-name {
      display: block;
      font-size: 30rpx;
      font-weight: 500;
      color: #333;
      margin-bottom: 12rpx;
    }

    .publisher-meta {
      display: flex;
      align-items: center;
      margin-bottom: 12rpx;

      .meta-icon {
        width: 24rpx;
        height: 24rpx;
        margin-right: 8rpx;
      }

      .meta-text {
        font-size: 24rpx;
        color: #666;
      }
    }

    .publisher-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 12rpx;

      .tag-item {
        padding: 6rpx 16rpx;
        background-color: #F6F6F8;
        color: #666;
        font-size: 22rpx;
        border-radius: 20rpx;
        white-space: nowrap;
      }
    }
  }
}

.participants-section {

  .section-title {
    display: block;
    font-size: 28rpx;
    font-weight: 500;
    color: #333;
    margin-bottom: 20rpx;
  }

  .participants-list {
    display: flex;
    align-items: center;
    gap: 20rpx;

    .participant-avatar {
      width: 80rpx;
      height: 80rpx;
      border-radius: 50%;
      border: 3rpx solid #fff;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
      cursor: pointer;
      transition: opacity 0.2s;
      
      &:active {
        opacity: 0.7;
      }
    }
  }
}

.location-section {

  .section-title {
    display: block;
    font-size: 28rpx;
    font-weight: 500;
    color: #333;
    margin-bottom: 20rpx;
  }

  .location-info {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;

    .location-icon {
      width: 24rpx;
      height: 24rpx;
      margin-right: 12rpx;
      flex-shrink: 0;
    }

    .location-text {
      font-size: 26rpx;
      color: #666;
      flex: 1;
    }
  }

  .map-container {
    width: 100%;
    height: 400rpx;
    border-radius: 16rpx;
    overflow: hidden;
    margin-top: 20rpx;

    .detail-map {
      width: 100%;
      height: 100%;
    }
  }

  /* 隐藏高德地图logo */
  .detail-map :deep(.amap-logo),
  .detail-map :deep(.amap-copyright) {
    display: none !important;
  }
}

.content-section {

  .section-title {
    display: block;
    font-size: 28rpx;
    font-weight: 500;
    color: #333;
    margin-bottom: 20rpx;
  }

  .content-text {
    display: block;
    font-size: 26rpx;
    color: #666;
    line-height: 1.8;
    white-space: pre-wrap;
    word-break: break-all;
    margin-bottom: 20rpx;
  }

  .images-section {
    display: flex;
    flex-direction: column;
    gap: 20rpx;
    margin-top: 20rpx;

    .content-image {
      width: 100%;
      height: 400rpx;
      border-radius: 16rpx;
      object-fit: cover;
    }
  }
}

.bottom-action-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: center;
  gap: 20rpx;
  padding: 20rpx 30rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  padding-bottom: calc(20rpx + constant(safe-area-inset-bottom));
  background-color: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
  z-index: 999;

  .contact-btn {
    width: 280rpx;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    background-color: #fff;
    border: 2rpx solid #e0e0e0;
    border-radius: 40rpx;
    font-size: 28rpx;
    color: #333;

    &::after {
      border: none;
    }
  }

  .join-btn {
    width: 280rpx;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    background: linear-gradient(90deg, #B276FF 0%, #74A7FF 100%);
    border-radius: 40rpx;
    font-size: 28rpx;
    color: #fff;

    &::after {
      border: none;
    }

    &.button-disabled,
    &:disabled {
      opacity: 0.6;
    }
  }
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.9);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;

  .loading-text {
    font-size: 28rpx;
    color: #999;
  }
}
</style>

<style lang="scss">
/* 全局隐藏高德地图logo */
.amap-logo,
.amap-copyright {
  display: none !important;
  opacity: 0 !important;
  visibility: hidden !important;
}

/* H5平台隐藏地图logo */
/* #ifdef H5 */
map {
  .amap-logo,
  .amap-copyright {
    display: none !important;
  }
}
/* #endif */
</style>
